/**
  ******************************************************************************
  * @file    mg_driver_iap.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2020 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */

#include "mg_driver_int.h"
#include "mg_driver_mtp.h"
#include "mg_driver_sys.h"

#include "mg_driver_iap.h"

void WriteBefore(void)
{
    DisableEnvINT();
    SYS_MG_ROM_CFG->CCR = 0x0C;//disable
}

void WriteAfter(void)
{
    SYS_MG_ROM_CFG->CCR = 0x08; //enable
    SYS_MG_ROM_CFG->CCR = 0x0C;
    while(!(SYS_MG_ROM_CFG->SR & 0x10));
    SYS_MG_ROM_CFG->CCR = 0x0D; 
    
    EnableEnvINT();
}

void IAP_Program(u8* data/*MUST be SRAM addr*/,u8 len/*MUST be 4 bytes aligned*/, u32 pos/*MUST be 4 bytes aligned*/)
{
//    u32 t;
    
//    t = SysCtrl->RESET_CTRL;
    
    //******* !!!! IMPORTANT !!!! ******************
    //if(pos <  1024+512)return; //boot zone
    if(pos <  16*1024)return; //bankA zone
    if(pos >= 30*1024+512)return;//user data zone
    
    WriteBefore();
    
    ProgramPage (pos, len, data);

//    SysCtrl->RESET_CTRL = t & 0xF7;//reset
    WriteAfter();
}

void IAP_EraseSector(u32 adr)
{
//    u32 t;
    
//    t = SysCtrl->RESET_CTRL;
    WriteBefore();
    
    EraseSector(adr);
    
//    SysCtrl->RESET_CTRL = t & 0xF7;//reset
    WriteAfter();
}

//BLE OTA_Proc() callback porting function.
void Write2MgROM(u8* data,u8 len, u32 pos)
{
    IAP_Program(data,len,pos);
}
